<template>
  <div :class="className" :style="{height:height,width:width}" />
</template>

<script>
import echarts from 'echarts'
require('echarts/theme/macarons') // echarts theme
import { debounce } from '@/utils'
import { mapGetters } from 'vuex'
import { nation } from '@/api/anniversary/statistics'

export default {
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '100%'
    },
    height: {
      type: String,
      default: '300px'
    }
  },
  data() {
    return {
      nationData: [],
      top: 10,
      chart: null
    }
  },
  computed: {
    ...mapGetters([
      'user'
    ])
  },
  mounted() {
    setTimeout(() => {
      var params = {}
      for (var i = 0; i < this.user.roles.length; i++) {
        if (this.user.roles[0].name === '学院管理员') {
          params = { college: this.user.dept.name, top: this.top + 1 }
        } else {
          params = { college: '', top: this.top + 1 }
        }
      }
      nation(params).then(res => {
        if (res != null) {
          for (var i = 1; i < res.length; i++) {
            this.nationData.push({ name: res[i].name, value: res[i].count })
          }

          this.initChart()
          this.__resizeHandler = debounce(() => {
            if (this.chart) {
              this.chart.resize()
            }
          }, 100)
          window.addEventListener('resize', this.__resizeHandler)
        }
      }
      )
    }, 100)
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    window.removeEventListener('resize', this.__resizeHandler)
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    initChart() {
      this.chart = echarts.init(this.$el, 'macarons')

      this.chart.setOption({
        title: {
          text: '少数民族校友分布Top ' + this.top,
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: '{b} : {c}人 ({d}%)'
        },
        calculable: true,
        series: [
          {
            type: 'pie',
            roseType: 'radius',
            radius: [15, 95],
            center: ['50%', '55%'],
            data: this.nationData,
            animationEasing: 'cubicInOut',
            animationDuration: 2600
          }
        ]
      })
    }
  }
}
</script>
